package com.futvan.z.framework.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;

/**
 * Bean工具类
 * @author 4223947@qq.com
 *
 */
public class BeanUtil {
	/**
	 * Bean转Map
	 * @param bean
	 * @return
	 */
	public static HashMap<String,String> BeanToMap(Object bean){
		HashMap<String,String> map = new HashMap<String, String>();
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor property : propertyDescriptors) {
				String key = property.getName();
				// 过滤class属性
				if (!key.equals("class")) {
					// 得到property对应的getter方法
					Method getter = property.getReadMethod();
					Object value = getter.invoke(bean);
					map.put(key, String.valueOf(value));
				}else {
					//获取表名
					map.put("tableId", bean.getClass().getSimpleName());
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	/** 
	 * Map转换层Bean，使用泛型免去了类型转换的麻烦。 
	 * @param <T> 
	 * @param map   
	 * @param class1 
	 * @return 
	 */  
	public static <T> T MapToBean(Map<String, String> map, Class<T> class1) {  
		T bean = null;  
		try {  
			bean = class1.newInstance();  
			BeanUtils.populate(bean, map);  
		} catch (Exception e) {  
			e.printStackTrace();  
		} 
		return bean;  
	}

}
